package model

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
)

type RoomBasic struct {
	Identity     string `bson:"identity"`
	Number       string `bson:"number"`
	Name         string `bson:"name"`
	Info         string `bson:"info"`
	UserIdentity string `bson:"user_identity"`
	CreatedAt    int64  `bson:"created_at"`
	UpdatedAt    int64  `bson:"updated_at"`
}

func (RoomBasic) CollectionName() string {
	return "room_basic"
}

func InsertOneRoomBasic(rb *RoomBasic) error {
	_, err := Mongo.Collection(RoomBasic{}.CollectionName()).
		InsertOne(context.Background(), rb)
	return err
}

func DeleteRoomBasic(roomIdentity string) error {
	_, err := Mongo.Collection(RoomBasic{}.CollectionName()).
		DeleteOne(context.Background(),
			bson.M{"identity": roomIdentity})

	if err != nil {
		log.Println("failed to delete room: ", err)
		return err
	}

	return nil
}

func UpdateRoomInfo(roomId, number, name, info string) error {
	collection := Mongo.Collection(RoomBasic{}.CollectionName())

	update := bson.D{
		{"$set", bson.D{
			{"number", number},
			{"name", name},
			{"info", info},
			{"updated_at", time.Now().Unix()},
		}},
	}

	log.Println(update)
	_, err := collection.UpdateOne(context.Background(), bson.D{{"identity", roomId}}, update)
	return err
}

// 检查用户是否有权限编辑房间（现在允许房间内的所有用户编辑）
func UserHasRoomAccess(userId, roomId string) bool {
	collection := Mongo.Collection(UserRoom{}.CollectionName())
	var userRoom UserRoom
	err := collection.FindOne(context.Background(), bson.D{
		{"user_identity", userId},
		{"room_identity", roomId},
	}).Decode(&userRoom)
	if err != nil {
		return false
	}

	log.Println(userRoom)
	return true
}
